import { isVideoDistribution } from "./checkEnv";
import { MARKETING_TEAM_BUY, MARKETING_SEC_KILL, KEY_ORDER_DETAILS, PAY_SUCCESS_URL, PAY_FAIL_URL } from "../constants";
import qs from 'qs';

export const debounce = (func, wait, immediate) => {
    let timer;

    return function () {
        //this指向debounce
        let context = this;
        //即参数，func,wait
        let args = arguments;

        //如果timer不为null, 清除定时器
        if (timer) clearTimeout(timer);

        //如果是立即执行
        if (immediate) {
            //定义callNow = !timer
            var callNow = !timer;
            //定义wait时间后把timer变为null
            //即在wait时间之后事件才会有效
            timer = setTimeout(() => {
                timer = null;
            }, wait)
            //如果callNow为true,即原本timer为null
            //那么执行func函数
            if (callNow) func.apply(context, args)
        } else {
            //如果是不立即执行
            //那就是每次重新定时
            timer = setTimeout(function () {
                func.apply(context, args)
            }, wait);
        }
    }
}

//如果是视频号，保存数据到localStorage
export function setDataIfWxChannel(key, value) {
    if (isVideoDistribution && value) {
        localStorage.setItem(key, JSON.stringify(value));
    }
}

//如果是视频号，从localStorage获取数据
export function getDataIfWxChannel(key) {
    if (isVideoDistribution) {
        const content = localStorage.getItem(key);
        return content && JSON.parse(content);
    }
}

// 根据相对url获取完整url
export const getUrl = (route, appId) => {
    let now_url = window.location.href.split("?")[0];
    //端口
    let protocol = window.location.protocol;
    //域名
    let hostname = window.location.hostname;
    // 业务id
    let app_id = window.APPID || appId;
    //根域名
    let root_url = "";
  
    if (app_id && hostname.indexOf(app_id) !== -1 && hostname.indexOf(app_id.toLowerCase()) !== -1) {
      //个人模式多域名
      root_url = protocol + "//" + hostname + "/";
    } else if (now_url.indexOf(".h5.") !== -1) {
      //企业模式
      root_url = protocol + "//" + hostname + "/";
    } else {
      //个人模式统一域名
      root_url = protocol + "//" + hostname + "/";
    }
    if (!route) {
      return root_url;
    }
  
    if (route !== "/" && route.indexOf("/") === 0) {
      route = route.substr(1);
    }
  
    return root_url + route;
};

// 重新组合商品数据，使商品组件可用
export function handleGoodsInfo(goodsList) {
    if (!goodsList) return [];
    return goodsList.map((goodsInfo) => {
        const { activity_type } = goodsInfo;
        goodsInfo.stock = goodsInfo.sku_info.sku_store?.left_num || 0; // sku库存
        goodsInfo.goods_stock = goodsInfo.sku_list.reduce((total, skuInfo) => {
            // 商品总库存
            return total + skuInfo.sku_store.left_num;
        }, 0);

        if (
            activity_type &&
            activity_type !== MARKETING_TEAM_BUY &&
            activity_type !== MARKETING_SEC_KILL
        ) {
            goodsInfo.piece_price = goodsInfo.sku_info.rate_sku_price;
        } else {
            goodsInfo.piece_price = goodsInfo.sku_info.sku_price;
        }
        if (goodsInfo.num) {
            // 商品数量
            goodsInfo.count = goodsInfo.num;
        }
        const maxBuyCount = goodsInfo.limit_purchase
            ? goodsInfo.limit_purchase - goodsInfo.has_buy_num
            : goodsInfo.stock;
        const limitBuy = maxBuyCount < goodsInfo.sku_min_purchase;
        goodsInfo.hasSvip = activity_type === 2 ? true : false;
        goodsInfo.invalidStock =
            goodsInfo.sku_info.is_deleted === 1 ||
            goodsInfo.stock === 0 ||
            goodsInfo.stock < goodsInfo.count;
        goodsInfo.checked =
            !limitBuy && goodsInfo.state === 1 && !goodsInfo.invalidStock
                ? true
                : false;
        goodsInfo.oldCheck = goodsInfo.checked; //保存接口获取的check态，防止编辑状态下更改了check态，能还原回去
        return goodsInfo;
    });
}

export function setOrderCache(paySuccessUrl, payFailUrl, orderResult) {
    sessionStorage.setItem(PAY_SUCCESS_URL, paySuccessUrl)
    sessionStorage.setItem(PAY_FAIL_URL, payFailUrl)
    if(typeof orderResult === 'object') {
        sessionStorage.setItem(KEY_ORDER_DETAILS, JSON.stringify(orderResult))
    }
}

export function getOrderCache() {
    const orderJSON = sessionStorage.getItem(KEY_ORDER_DETAILS);
    const order = orderJSON ? JSON.parse(orderJSON) : null;
    return {
        order,
        paySuccessUrl: sessionStorage.getItem(PAY_SUCCESS_URL),
        payFailUrl: sessionStorage.getItem(PAY_FAIL_URL)
    }
}

export function clearOrderCache() {
    sessionStorage.removeItem(KEY_ORDER_DETAILS)
    sessionStorage.removeItem(PAY_SUCCESS_URL)
    sessionStorage.removeItem(PAY_FAIL_URL)
}

export function isEmptyObject(obj) {
    return Object.keys(obj || {}).length === 0;
}

/**
 * 获取指定JS文件耗时
 * @param {Object} filename 文件路径名
 * @returns 返回文件加载耗时，-1为获取失败
 */
export function getFileTiming (filename) {
    // 使用 Performance API 获取所有资源的加载性能数据
    const entries = performance.getEntries();
    // 遍历资源数据，找到指定文件的加载时间
    for (let i in entries) {
        const entry = entries[i];
        if (entry.initiatorType === "script" && entry.name.match(filename)) {
            return entry.duration
        }
    }
    // 如果没有找到指定文件的加载时间，返回 -1 或其他自定义值
    return -1;
}


/**
 * 包装请求参数
 * @param {Object} params 参数
 * @param {String} wrap 包装的字符串
 * @returns 包装后的参数字符串
 */
export function packParams(params, wrap = 'bizData') {
    const obj = {};
    for (let key in params) {
        obj[`${wrap}[${key}]`] = params[key];
    }
    return qs.stringify(obj);
}

